package com.huilan.hgt.util;


import com.huilan.hgt.entity.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.Random;

/**
 * @Author ghy
 * @date 2018-11-02 18:17:58
 * 全局静态属性定义类
 */
public class Constants {


    /**
     * 存储在Redis中角色名称的key
     */
    public static final  String ROLE_ADMIN = "ROLE_ADMIN";



    /**
     * http状态码
     */
    public static class HTTP_STATUS {
        /**
         * Unauthorized
         * 请求要求用户的身份认证
         */
        public static final Integer CODE_401 = 401;
        /**
         * Forbidden
         * 服务器理解请求客户端的请求，但是拒绝执行此请求
         */
        public static final Integer CODE_403 = 403;
        /**
         * Not Found
         * 找不到系统资源
         */
        public static final Integer CODE_404 = 404;
        /**
         * Internal Server Error
         * 服务器内部错误，无法完成请求
         */
        public static final Integer CODE_500 = 500;

    }

    /**
     * 获取当前登录用户信息
     * @return
     */
    public static User getCurrentUser(){
        User userDetails = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        return userDetails;
    }


    /**
     * 获取当前登录用户的角色信息
     * @return
     */
    public static Collection getCurrentUserRoles(){
        Collection<? extends GrantedAuthority> authorities = SecurityContextHolder.getContext().getAuthentication().getAuthorities();
        return authorities;
    }

    /**
     * 判断当前用户角色是否是管理员
     */
    public static boolean isAdmin () {
        Collection currentUserRoles = Constants.getCurrentUserRoles();

        SimpleGrantedAuthority role = new SimpleGrantedAuthority(ROLE_ADMIN);
        return currentUserRoles.contains(role);
    }

    /**
     * 随机加密PIN码两位数字
     */
    public static String encryptionPin(Integer code){
        String pin = code.toString();
        int num1;
        int num2;
        do {
            num1 =new Random().nextInt(6)+1;
            num2 =new Random().nextInt(6)+1;
        }while(num1==num2);
        char str1 = pin.charAt(num1 - 1);
        char str2 = pin.charAt(num2 - 1);
        return pin.replace(str1, '*').replace(str2, '*');
    }
}

